﻿@*
    // Copyright (c) Alex Reich.
    // Licensed under the CC BY 4.0 License.
*@
@page "/DemoAlt"
@using Newtonsoft.Json
@using RulesEngine.Models
@using RulesEngineEditor.Models
@inject HttpClient Http

<RulesEngineEditorPage EditorRulesEngine="re" @bind-WorkflowDatas="WorkflowDatas" InputJSON="@Inputs" />

@code {
    private RulesEngine.RulesEngine re;

#if ConventionalJSON
private WorkflowRules[] _workflows;
private WorkflowRules[] Workflows { get { return _workflows; } set { _workflows = value; } }
#endif

    private List<WorkflowData> _workflowDatas = new List<WorkflowData>();
    private List<WorkflowData> WorkflowDatas
    {
        get { return _workflowDatas; }
        set { _workflowDatas = value; }
    }

    private string Inputs;

    enum FooEnum
    {
        bar = 123
    }

    protected override async Task OnInitializedAsync()
    {
        var settings = new ReSettings
        {
            CustomTypes = new Type[] { typeof(FooEnum) }
        };
        re = new RulesEngine.RulesEngine(new string[0], settings);

#if BasicDemo
List<WorkflowRules> workFlowRules = new List<WorkflowRules>();
WorkflowRules workflowRule = new WorkflowRules();
workflowRule.WorkflowName = "Test Workflow Rule 1";

List<Rule> rules = new List<Rule>();

Rule rule = new Rule();
rule.RuleName = "Test Rule";
rule.SuccessEvent = "Count is within tolerance.";
rule.ErrorMessage = "Over expected.";
rule.Expression = "count < 3";
rule.RuleExpressionType = RuleExpressionType.LambdaExpression;

rules.Add(rule);

workflowRule.Rules = rules;

workFlowRules.Add(workflowRule);

Workflows = workFlowRules.ToArray();
#endif
#if ConventionalJSON
var path = Path.Combine(Directory.GetCurrentDirectory(), @"..\TestData\");
var files = Directory.GetFiles(path, "Discount.json", SearchOption.AllDirectories);
if (files == null || files.Length == 0)
    throw new Exception("Rules not found.");

var fileData = File.ReadAllText(files[0]);
var workflow = JsonConvert.DeserializeObject<List<WorkflowRules>>(fileData);

files = Directory.GetFiles(path, "DiscountInputs.json", SearchOption.AllDirectories);
if (files == null || files.Length == 0)
    throw new Exception("Inputs not found.");

Workflows = workflow.ToArray();
Inputs = File.ReadAllText(files[0]);
#endif
        var file = await Http.GetAsync("sample-data/discount.json");
        var fileData = await file.Content.ReadAsStringAsync();
        WorkflowDatas = JsonConvert.DeserializeObject<List<WorkflowData>>(fileData);

        file = await Http.GetAsync("sample-data/discountInputs.json");
        Inputs = await file.Content.ReadAsStringAsync();

        //emulate EF some Ids
        for (int x = 0; x < WorkflowDatas.Count; x++)
        {
            WorkflowDatas[x].Id = x + 1;
            for (int y = 0; y < WorkflowDatas[x].Rules.Count; y++)
            {
                WorkflowDatas[x].Rules[y].Id = y + 1;
            }
        }

    }
}